package com.th.control;

import com.sun.deploy.net.HttpResponse;
import com.th.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;



@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${takeout.basepath}")
    private String basepath;
//特殊打算范德萨发生的
    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file 是一个临时文件，需要转存到指定位置，否则请求完成后临时文件会删除
        log.info("file:{}",file.toString());

        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String filename = UUID.randomUUID().toString()+suffix;

        System.out.println(filename);

        File dir = new File(basepath);

        if(!dir.exists()){
            dir.mkdir();
        }

        try {
            file.transferTo(new File(basepath+filename));
        }catch (IOException e){
            e.printStackTrace();
        }

        return R.success(filename);


    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
       try {
           FileInputStream fi = new FileInputStream(new File(basepath + name));
           ServletOutputStream os = response.getOutputStream();

           byte[] bytes =  new byte[1024];
           int len;
           while ((len = fi.read(bytes)) != -1){
                os.write(bytes,0,len);
           }
           fi.close();
           os.close();
       }catch (IOException io){
           io.printStackTrace();
       }


    }
}

